<?php
/**
 * 诊断菜单不显示的原因
 */

$host = '113.44.136.17';
$port = 3306;
$database = 'qiandao';
$username = 'qiandao';
$password = 'NGbks3HWx5PhSxDX';

try {
    $pdo = new PDO("mysql:host={$host};port={$port};dbname={$database};charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "=== 菜单显示条件诊断 ===\n\n";
    
    // 1. 检查菜单基本信息
    echo "【1】检查权限管理菜单的基本信息\n";
    $stmt = $pdo->query("SELECT id, pid, title, icon, node, url, params, target, sort, status FROM system_menu WHERE id = 9");
    $menu = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($menu) {
        echo "✓ 菜单存在\n";
        echo "  ID: {$menu['id']}\n";
        echo "  PID: {$menu['pid']}\n";
        echo "  标题: {$menu['title']}\n";
        echo "  图标: {$menu['icon']}\n";
        echo "  节点: {$menu['node']}\n";
        echo "  URL: {$menu['url']}\n";
        echo "  参数: {$menu['params']}\n";
        echo "  目标: {$menu['target']}\n";
        echo "  排序: {$menu['sort']}\n";
        echo "  状态: {$menu['status']} " . ($menu['status'] == 1 ? '(启用)' : '(禁用)') . "\n";
        
        // 检查条件1：status 必须为 1
        if ($menu['status'] != 1) {
            echo "\n❌ 问题：菜单状态为禁用！\n";
            echo "   解决：需要启用菜单\n";
        }
        
        // 检查条件2：如果是一级菜单（pid=0），必须有子菜单或者 url 不为空
        if ($menu['pid'] == 0) {
            echo "\n【2】检查一级菜单的子菜单\n";
            $stmt2 = $pdo->prepare("SELECT id, title, node, url, status FROM system_menu WHERE pid = ? AND status = 1");
            $stmt2->execute([$menu['id']]);
            $subMenus = $stmt2->fetchAll(PDO::FETCH_ASSOC);
            
            if (empty($subMenus)) {
                if (empty($menu['url']) || $menu['url'] === '#') {
                    echo "❌ 问题：一级菜单没有子菜单，且 URL 为空或 #\n";
                    echo "   解决：需要添加子菜单或设置有效的 URL\n";
                } else {
                    echo "✓ 一级菜单有有效的 URL: {$menu['url']}\n";
                }
            } else {
                echo "✓ 找到 " . count($subMenus) . " 个启用的子菜单：\n";
                foreach ($subMenus as $sub) {
                    echo "  - {$sub['title']} (节点: {$sub['node']}, URL: {$sub['url']})\n";
                    
                    // 检查子菜单的 node 或 url
                    if ((empty($sub['node']) || $sub['node'] === '#') && (empty($sub['url']) || $sub['url'] === '#')) {
                        echo "    ⚠️  警告：此子菜单的 node 和 url 都为空或 #\n";
                    }
                }
            }
        }
        
        // 检查条件3：检查子菜单的 node 是否有对应的控制器方法
        echo "\n【3】检查子菜单的控制器方法是否存在\n";
        $stmt3 = $pdo->prepare("SELECT id, title, node FROM system_menu WHERE pid = ? AND status = 1");
        $stmt3->execute([$menu['id']]);
        $subMenus = $stmt3->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($subMenus as $sub) {
            if (!empty($sub['node']) && $sub['node'] !== '#') {
                // 解析 node：admin/user/index -> app/admin/controller/User.php::index()
                $parts = explode('/', $sub['node']);
                if (count($parts) >= 3) {
                    $module = $parts[0];
                    $controller = ucfirst($parts[1]);
                    $action = $parts[2];
                    
                    $controllerFile = __DIR__ . "/app/{$module}/controller/{$controller}.php";
                    
                    if (file_exists($controllerFile)) {
                        echo "  ✓ {$sub['title']}: 控制器文件存在 ({$controllerFile})\n";
                        
                        // 检查方法是否存在
                        $content = file_get_contents($controllerFile);
                        if (preg_match("/function\s+{$action}\s*\(/", $content)) {
                            echo "    ✓ 方法 {$action}() 存在\n";
                        } else {
                            echo "    ❌ 方法 {$action}() 不存在\n";
                        }
                    } else {
                        echo "  ❌ {$sub['title']}: 控制器文件不存在 ({$controllerFile})\n";
                    }
                }
            }
        }
        
    } else {
        echo "❌ 菜单不存在（ID:9）\n";
    }
    
    // 4. 检查是否有 URL 字段为空的问题
    echo "\n【4】检查所有一级菜单的 URL 和子菜单情况\n";
    $stmt = $pdo->query("SELECT id, title, url, status FROM system_menu WHERE pid = 0 ORDER BY sort DESC, id ASC");
    $topMenus = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($topMenus as $top) {
        $status = $top['status'] == 1 ? '启用' : '禁用';
        echo "\n{$top['title']} (ID:{$top['id']}, URL:{$top['url']}, {$status})\n";
        
        if ($top['status'] == 1) {
            $stmt2 = $pdo->prepare("SELECT COUNT(*) as cnt FROM system_menu WHERE pid = ? AND status = 1");
            $stmt2->execute([$top['id']]);
            $count = $stmt2->fetch(PDO::FETCH_ASSOC)['cnt'];
            
            if ($count > 0) {
                echo "  ✓ 有 {$count} 个启用的子菜单\n";
            } else {
                if (empty($top['url']) || $top['url'] === '#') {
                    echo "  ❌ 没有子菜单，且 URL 为空或 #，此菜单会被过滤掉！\n";
                } else {
                    echo "  ✓ 没有子菜单，但有有效的 URL: {$top['url']}\n";
                }
            }
        }
    }
    
    echo "\n\n=== 诊断总结 ===\n";
    echo "菜单显示的必要条件：\n";
    echo "1. status = 1 (启用状态)\n";
    echo "2. 如果是一级菜单且 url 为空或 #，必须有至少一个启用的子菜单\n";
    echo "3. 如果是二级菜单，必须有有效的 node 或 url\n";
    echo "4. 如果有 node，对应的控制器方法必须存在且有权限访问\n";
    echo "5. 超级管理员（admin）可以看到所有菜单，普通用户需要分配权限\n";
    
} catch (PDOException $e) {
    echo "数据库错误: " . $e->getMessage() . "\n";
}

